package xyz.yuzegod.megawalls.timer;

import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.util.Vector;
import xyz.yuzegod.megawalls.game.Game;
import xyz.yuzegod.megawalls.game.GamePlayer;
import xyz.yuzegod.megawalls.game.GameTeam;
import xyz.yuzegod.megawalls.util.PlayerUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class WitherSpecialAttackTimer extends BukkitRunnable
{
    private Game game;
    private boolean state;
    
    public WitherSpecialAttackTimer(final Game game) {
        this.state = true;
        this.game = game;
    }
    
    public void run() {
        if (!this.game.isWitherAngry()) {
            return;
        }
        this.state = !this.state;
        for (final GameTeam gameTeam : this.game.getTeams()) {
            if (!gameTeam.isWitherDead() && this.game.isWitherAngry()) {
                for (final Player other : PlayerUtils.getNearbyPlayers(gameTeam.getWitherLocation(), 5.0)) {
                    final GamePlayer gamePlayer = GamePlayer.get(other.getUniqueId());
                    if (!gamePlayer.isSpectator()) {
                        if (gameTeam.isInTeam(gamePlayer)) {
                            continue;
                        }
                        if (this.state) {
                            other.setVelocity(new Vector(0.0, 1.0, 0.0));
                            gamePlayer.sendMessage("§c" + gameTeam.getTeamColor().getText() + "队凋零正在蓄力发动冲击波！");
                        }
                        else {
                            final Vector vector = other.getLocation().getDirection();
                            other.setVelocity(new Vector(-0.5 * vector.getX(), 0.0, -0.5 * vector.getZ()));
                            gamePlayer.sendMessage("§c" + gameTeam.getTeamColor().getText() + "队凋零正在蓄力击退！");
                        }
                        if(other.getHealth()<=0|| ((int) (other.getHealth() / 2.0))<=0) {
                            other.damage((double) new Random().nextInt(1));
                        }else {
                            other.damage((double) new Random().nextInt((int) (other.getHealth() / 2.0)));
                        }
                    }
                }
            }
        }
    }
    
    private List<Player> getNearbyPlayers(final Player player, final int radius) {
        final List<Player> players = new ArrayList<Player>();
        for (final Player other : PlayerUtils.getNearbyPlayers((Entity)player, radius)) {
            final GamePlayer gameOther = GamePlayer.get(other.getUniqueId());
            if (!gameOther.isSpectator()) {
                if (GamePlayer.get(player.getUniqueId()).getGameTeam().isInTeam(gameOther)) {
                    continue;
                }
                players.add(other);
            }
        }
        return players;
    }
}
